//
//  SystemSettting.m
//  GKBHouse
//
//  Created by  on 12-7-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SystemSettting.h"
#import "GKBNavigationBar.h"
#import "iToast.h"
#import "Global1.h"
NSString *urlString;
@implementation SystemSettting
@synthesize sortTypes;
@synthesize sortSelectedIndex;
//@synthesize refreshTypes;
//@synthesize refreshIndex;
@synthesize successLoginUserArray;

+ (NSString *)systemSetFilePath
{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths    objectAtIndex:0];
    NSString *fileName = @"systemset.dat";
    NSString *filePath = [path stringByAppendingFormat:@"/%@", fileName];
    return filePath;
}
+ (NSString *)systemSettingType:(NSString *)type
{
    NSString *file = [SystemSettting systemSetFilePath];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:file];
    // NSString *server = [dic objectForKey:@"server"];
    NSString *typeStr = [dic objectForKey:type];
    return typeStr;    
}

+ (NSString *)systemUrl
{
    NSString *host = [SystemSettting systemSettingType:@"server"];
    if (!host) {
        host = @"www.gkbhome.com";
    }
//    NSString *port = [SystemSettting systemSettingType:@"port"];
//    if (!port) {
//        port = @"8001";
//    }
    
    NSString *url = [NSString stringWithFormat:@"http://%@/gkbws/services/AIClientWebservice?wsdl",host];
    return url;
    
//    NSString *url = [NSString stringWithFormat:@"http://%@:%@/gkbws/services/AIClientWebservice?wsdl",host, port];
//    return url;
//    if (!urlString) {
//       
//        urlString = [url copy];
//    }    
//    return urlString;
}
+ (NSInteger)systemRate
{
    NSInteger refreshRates[] = {5, 10, 15, 25};
    NSInteger rateIndex = 3;
    NSString *rate = [SystemSettting systemSettingType:@"rate"];
    if (rate) {
        rateIndex = rate.integerValue;
    }
    NSInteger rateTime = refreshRates[rateIndex];
    return rateTime;
}
+ (NSInteger)sortType
{
    NSInteger sortType[] = {1, 2, 3, 4};
    NSInteger sortIndex = 0;
    NSString *sort = [SystemSettting systemSettingType:@"sort"];
    if (sort) {
        sortIndex = sort.integerValue;
    }
    NSInteger type = sortType[sortIndex];
    return type;
}
+ (NSString *)localUserName
{
    NSString *localUser = [SystemSettting systemSettingType:@"localUser"];
    if (localUser == nil || [localUser isEqualToString:@""]) {
        return nil;
    }
    return localUser;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    //排序类型
    self.sortSelectedIndex = 0;
    self.sortTypes = [NSArray arrayWithObjects:NSLocalizedString(@"switchId", nil),
                      NSLocalizedString(@"equipmentName", nil),
                      NSLocalizedString(@"tagName", nil),
                      NSLocalizedString(@"Self-defined serial No", nil), nil];
    //刷新时间
    //self.sortSelectedIndex = 3;
   // self.refreshTypes = [NSArray arrayWithObjects:NSLocalizedString(@"5s", nil),
   //                   NSLocalizedString(@"10s", nil),
   //                   NSLocalizedString(@"15s", nil),
   //                   NSLocalizedString(@"25s", nil), nil];
    
    self.successLoginUserArray = [AppFile successLoginUserArray];
    [self initTopBar];
    [self initVerificationView];
    
    [self initLabel];
    [self initSystemSet];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}
- (void)initTopBar
{    
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"systemSetting", nil)];
    [self.view addSubview:topBar];    
    [topBar release];

    
}
- (void)initVerificationView
{
    GKBNavigationBar *verificationTop = [[GKBNavigationBar alloc]init];
    [verificationTop setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"systemSetting", nil)];
    [verificationView addSubview:verificationTop];
    [verificationTop release];
    
    [verificationView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [verifiTitle setText:NSLocalizedString(@"inputPassword:", nil)];
    [passTip setText:NSLocalizedString(@"password:", nil)];
    [verifiOk setTitle:NSLocalizedString(@"ok", nil) forState:UIControlStateNormal];
    [verifiOk addTarget:self action:@selector(verifiOkAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:verificationView];
}
- (void)verifiOkAction
{
    if ([passWord.text isEqualToString:@"000000"]) {
        [self removeVerifi];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"passWordError", nil);
        [iToast showTip:tip gravity:iToastGravityTop];
    }
    
}
- (void)removeVerifi
{
    [verificationView removeFromSuperview];
}
- (void)dismissView
{
    [self dismissModalViewControllerAnimated:NO];
}
- (void)initLabel
{
    [serverLabel setText:NSLocalizedString(@"server address", nil)];
    [hostLabel setText:NSLocalizedString(@"host IP", nil)];
    [portLabel setText:NSLocalizedString(@"port number", nil)];
 //   [unitLabel setText:NSLocalizedString(@"63/112", nil)];
    [datasortLabel setText:NSLocalizedString(@"data sort", nil)];
//    [refreshRateLabel setText:NSLocalizedString(@"refreshRate", nil)];
    [localUserLabel setText:NSLocalizedString(@"localModel User", nil)];
    
//    [button63 addTarget:self action:@selector(unitSelected:) forControlEvents:UIControlEventTouchUpInside];
//    [button112 addTarget:self action:@selector(unitSelected:) forControlEvents:UIControlEventTouchUpInside];
    
    [sortButton addTarget:self action:@selector(sortButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
//    [refreshRateButton addTarget:self action:@selector(refreshButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [localUserButton addTarget:self action:@selector(localUserButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [setOk setTitle:NSLocalizedString(@"ok", nil) forState:UIControlStateNormal];
    [setOk addTarget:self action:@selector(setOkAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)initSystemSet
{
    NSString *file = [SystemSettting systemSetFilePath];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:file];
    NSString *server = [dic objectForKey:@"server"];
    NSString *host = [dic objectForKey:@"host"];
    NSString *port = [dic objectForKey:@"port"];
//    NSString *unit = [dic objectForKey:@"unit"];
    NSString *sort = [dic objectForKey:@"sort"];
//    NSString *rate = [dic objectForKey:@"rate"];
    NSString *localUser = [dic objectForKey:@"localUser"];
    if (server) {
        [serverText setText:server];
    }
    if (!host) {
        host = @"192.168.0.168";
    }
    if (!port) {
        port = @"8001";
    }
    [hostText setText:host];
    [portText setText:port];
    
//    if ([unit isEqualToString:@"112"]) {
//        button63.selected = NO;
//        button112.selected = YES;
//    }
//    else
//    {
//        button63.selected = YES;
//        button112.selected = NO;
//    }
    
    if (sort) {
        self.sortSelectedIndex = sort.integerValue;
    }
    else
    {
        self.sortSelectedIndex = 0;
    }
    

    NSString *sortStr = [self.sortTypes objectAtIndex:self.sortSelectedIndex];
    [sortText setText:sortStr];
    
//    if (rate) {
//        self.refreshIndex = rate.integerValue;
//    }
//    else
//    {
//        self.refreshIndex = 3;//默认第4个
//    }

//    NSString *rateStr = [self.refreshTypes objectAtIndex:self.refreshIndex ];
//    [refreshRateText setText:rateStr];
    
    if (localUser) {
        [localUserText setText:localUser];
    }
    
}


- (void)setOkAction
{
    NSMutableDictionary *setDic = [NSMutableDictionary dictionary];
    
    NSString *server = serverText.text;
    NSString *host = hostText.text;
    NSString *port = portText.text;
//    NSString *unit = @"";
//    if (button112.selected) {
//        unit = @"112";
//    }
//    else
//    {
//        unit = @"63";
//    }
    NSString *sort = [NSString stringWithFormat:@"%d",self.sortSelectedIndex];
//    NSString *rate = [NSString stringWithFormat:@"%d",self.refreshIndex];
    NSString *localUser = localUserText.text;
    
    [setDic setValue:server forKey:@"server"];
    [setDic setValue:host forKey:@"host"];
    [setDic setValue:port forKey:@"port"];
//    [setDic setValue:unit forKey:@"unit"];
    [setDic setValue:sort forKey:@"sort"];
//    [setDic setValue:rate forKey:@"rate"];
    [setDic setValue:localUser forKey:@"localUser"];
    
    NSString *filePath = [SystemSettting systemSetFilePath];
    
    BOOL save = [setDic writeToFile:filePath atomically:YES];
    
    if (!save) {
        return;
    }
    if ([LoginController1 loginType] == LoginTypeLocal)//本地登录模式切换用户，更新对应场景
    {
        NSString *localUser = [SystemSettting localUserName];
        if (localUser) {//有绑定用户才更新
            [LoginController1 setCurrentUser:localUser];
            GKBMainController *main = [GKBMainController mainCtr];
            if (main) [main initScene];
            [GKBMainController refreshDevices];
        }
        
    }
    [self dismissView];
    NSString *success = NSLocalizedString(@"Set Success", nil);
    [iToast showTip:success gravity:iToastGravityCenter];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//- (void)unitSelected:(UIButton *)but
//{
//    if (!but.selected) {
//        but.selected = YES;
//        if (but == button63) {
//            button112.selected = NO;
//        }
//        else
//        {
//            button63.selected = NO;
//        }
//    }
//}
- (void)sortButtonAction
{
    UIActionSheet *sheet = [[UIActionSheet alloc]init];
    sheet.delegate = self;
    sheet.tag = 0;
    for (NSString *title in self.sortTypes) {
        [sheet addButtonWithTitle:title];
    }
    NSInteger canel = [sheet addButtonWithTitle:NSLocalizedString(@"cancel", nil)];
    
    [sheet setCancelButtonIndex:canel];
    [sheet showInView:self.view];
    [sheet release];
}
//- (void)refreshButtonAction
//{
//    UIActionSheet *sheet = [[UIActionSheet alloc]init];
//    sheet.delegate = self;
//    sheet.tag = 1;
//    for (NSString *title in self.refreshTypes) {
//        [sheet addButtonWithTitle:title];
//    }
//    NSInteger canel = [sheet addButtonWithTitle:NSLocalizedString(@"cancel", nil)];
//    
//    [sheet setCancelButtonIndex:canel];
//    [sheet showInView:self.view];
//    [sheet release];
//}
- (void)localUserButtonAction
{
    UIActionSheet *sheet = [[UIActionSheet alloc]init];
    sheet.delegate = self;
    sheet.tag = 2;
    for (NSString *title in self.successLoginUserArray) {
        [sheet addButtonWithTitle:title];
    }
    NSInteger canel = [sheet addButtonWithTitle:NSLocalizedString(@"cancel", nil)];
    
    [sheet setCancelButtonIndex:canel];
    [sheet showInView:self.view];
    [sheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(actionSheet.cancelButtonIndex != buttonIndex)
    {
        if (actionSheet.tag == 0) {
            NSString *title = [self.sortTypes objectAtIndex:buttonIndex];
            [sortText setText:title];
            self.sortSelectedIndex = buttonIndex;
        }
        if (actionSheet.tag == 1) {
//            NSString *title = [self.refreshTypes objectAtIndex:buttonIndex];
//            [refreshRateText setText:title];
//            self.refreshIndex = buttonIndex;
        }
        if (actionSheet.tag == 2) {
            NSString *title = [self.successLoginUserArray objectAtIndex:buttonIndex];
            [localUserText setText:title];
        }
    }
  
    
}
@end
